﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;

using CM.AgileConfig.Client;

namespace OnFrameworkTest
{
    class Program
    {
        static void Main()
        {
            /*
              sudo docker run \
                --name agile_config \
                -e adminConsole=true \
                -e db:provider=sqlite \
                -e db:conn="Data Source=agile_config.db" \
                -p 5000:5000 \
                -d kklldog/agile_config:latest
            */

            Console.WriteLine("hello start .");

            //应用ID
            var appId = "ff75aba4-234e-4224-806f-f06671675cbe";
            //密钥
            var secret = "ff75aba4-234e-4224-806f-f06671675cbe";
            //环境
            var env = string.Empty;
            //节点 多个节点使用逗号分隔
            var nodes = "http://localhost:5000/";

            //使用有参构造函数，手动传入appid等信息 logger 用于打印内部信息,可空

            var client = new ConfigClient(appId, secret, nodes, env,
                logger => Console.WriteLine($"{DateTime.Now:O}->{logger}"))
            //var client = new ConfigClient(appId, secret, nodes, env, null)
            {
                //客户端名称
                Name = "OnFrameworkTest",
                //非必填
                Tag = "Client"
            };

            //配置变更事件
            //client.ConfigChanged += Client_ConfigChanged;

            //启动
            _ = client.ConnectAsync().ConfigureAwait(false);

            _ = Task.Factory.StartNew(async () =>
              {
                  Stopwatch stopwatch = new Stopwatch();
                  stopwatch.Start();
                  while (true)
                  {
                      await Task.Delay(1000);

                      //配置在client.Data.Keys字典里
                      foreach (string key in client.Data.Keys)
                      {
                          var val = client[key];
                          Console.WriteLine("{3} {0} : {1} 获取耗时: {2}", key, val, stopwatch.ElapsedMilliseconds,DateTime.Now.ToLongTimeString());
                          stopwatch.Reset();
                      }
                  }
              }, TaskCreationOptions.LongRunning);

            Console.ReadLine();

        }

        private static void Client_ConfigChanged(ConfigChangedArg obj)
        {
            Console.WriteLine("数据有变化了 {0} {1}", obj.Action, obj.Key);
        }
    }
}
